//  ======================= 地址栏携带id和type参数
function getHashParams() {
    const hash = window.location.hash.substring(1); // 去掉开头的#
    const params = new URLSearchParams(hash);
    return {
        cid: params.get("id") || "",
        ctype: params.get("type") || "",
    };
}
// 使用示例
//   const { id, type } = getHashParams();
//   console.log("ID:", id, "Type:", type);

// ======================= 标签页标题
function getUrlParam(param) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(param);
}

const languageMap = {
    en: "英语",
    fr: "法语",
    de: "德语",
    it: "意大利",
    es: "西班牙",
    "zh-CN": "中文简体",
    nl: "荷兰",
    sv: "瑞典",
    pl: "波兰",
};

document.querySelector("head > title").textContent =
    languageMap[getUrlParam("tl")];
// 存储当前的tl值
let currentTlValue = new URLSearchParams(window.location.search).get("tl");

// 定义一个函数来检查tl参数的变化
function checkTlChange() {
    const newTlValue = new URLSearchParams(window.location.search).get("tl");
    if (newTlValue !== currentTlValue) {
        console.log(`tl 参数已更改：从 ${currentTlValue} 到 ${newTlValue}`);
        document.querySelector("head > title").textContent =
            languageMap[newTlValue];
        currentTlValue = newTlValue; // 更新当前值以便下次比较
    }
}

// 初始化检查（以防页面加载时已经有tl参数）
checkTlChange();

// 设置一个观察者来监听URL的变化（注意：这种方法可能无法直接捕获所有URL变化，特别是由JavaScript动态更改的）
// 由于Google Translate页面可能不会通过传统的history API更改URL（例如，使用pushState），我们需要一个不同的策略
// 在这个场景中，我们可以使用MutationObserver来观察location对象的属性变化，但location对象的变化通常会导致页面重新加载
// 因此，更实用的方法是轮询或使用其他事件监听机制（如果可用）
// 然而，为了简化示例，我们将使用轮询
setInterval(checkTlChange, 1000); // 每秒检查一次

// 注意：轮询可能不是最高效的方法，但它在这个简单的示例中是可行的
// 在生产环境中，你可能需要寻找更优雅的解决方案来监听URL变化




// ======================= 切换语言按钮
let switchLanguage = document.createElement("div");
switchLanguage.style.position = "fixed";
switchLanguage.style.top = "3px";
switchLanguage.style.left = "50.2%";
switchLanguage.style.width = "615px";
switchLanguage.style.backgroundColor = "#f9f9f9";
switchLanguage.style.padding = "10px";
switchLanguage.style.border = "1px solid #ddd";
switchLanguage.style.borderRadius = "8px";
switchLanguage.style.zIndex = "10000";
const languages = [
    "中文",
    "英语",
    "法语",
    "德语",
    "意大利",
    "西班牙",
    "荷兰",
    "瑞典",
    "波兰",
];
const countries = ["zh-CN", "en", "fr", "de", "it", "es", "nl", "sv", "pl"];
for (let i = 0; i < languages.length; i++) {
    let button = document.createElement("button");
    button.textContent = languages[i];
    button.addEventListener("click", () => {
        let url = window.location.href;
        let tl = url.match(/&tl=[^&]+&/);
        url = url.replace(tl[0], "&tl=" + countries[i] + "&");
        window.open(url, "_self");
    });
    button.style.marginLeft = "12px";
    button.style.marginRight = "10px";
    button.style.height = "40px";
    switchLanguage.appendChild(button);
}
document.body.appendChild(switchLanguage);


window.onload = function () {


    // ======================= 复制按钮容器
    let copy = document.createElement("div");
    copy.style.position = "fixed";
    copy.style.top = "3px";
    copy.style.left = "35.4%";
    copy.style.width = "250px";
    copy.style.backgroundColor = "#f9f9f9";
    copy.style.padding = "10px";
    copy.style.border = "1px solid #ddd";
    copy.style.borderRadius = "8px";
    copy.style.zIndex = "10000";

    // ======================= 复制原文按钮
    let bt_yuanwen = document.createElement("button");
    bt_yuanwen.textContent = "复制原文";
    bt_yuanwen.addEventListener("click", function () {
        let txt = document.querySelector(
            "#yDmH0d > c-wiz > div > div.ToWKne > c-wiz > div.OlSOob > c-wiz > div.ccvoYb > div.AxqVh > div.OPPzxe > div > c-wiz > span > span > div > div.hlJJmd > div.D5aOJc.Hapztf"
        ).textContent;
        const textarea = document.createElement("textarea");
        textarea.value = txt;
        textarea.style.position = "absolute";
        textarea.style.opacity = "0";
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand("copy");
        document.body.removeChild(textarea);
    });
    bt_yuanwen.style.height = "40px";
    bt_yuanwen.style.width = "120px";
    copy.appendChild(bt_yuanwen);


    // ======================= 复制译文按钮
    let bt_copy = document.createElement("button");
    bt_copy.textContent = "复制译文";
    bt_copy.addEventListener("click", function () {
        document
            .querySelector(
                "#yDmH0d > c-wiz > div > div.ToWKne > c-wiz > div.OlSOob > c-wiz > div.ccvoYb > div.AxqVh > div.OPPzxe > c-wiz > div > div.usGWQd > div > div.VO9ucd > div.YJGJsb > span:nth-child(2) > button"
            ).click();
    });
    bt_copy.style.marginLeft = "10px";
    // bt_copy.style.marginRight = '10px';
    bt_copy.style.height = "40px";
    bt_copy.style.width = "120px";
    copy.appendChild(bt_copy);
    document.body.appendChild(copy);




    // ======================= 翻译结果检查器

    const elementChecker = setInterval(() => {
        const selector = "#yDmH0d > c-wiz > div > div.ToWKne > c-wiz > div.OlSOob > c-wiz > div.ccvoYb > div.AxqVh > div.OPPzxe > c-wiz > div > div.usGWQd > div > div.lRu31 > span.HwtZe";
        const targetElement = document.querySelector(selector);
        if (targetElement) {
            let text = "";
            for (let i = 1; ; i++) {
                let child = document.querySelector(
                    "#yDmH0d > c-wiz > div > div.ToWKne > c-wiz > div.OlSOob > c-wiz > div.ccvoYb > div.AxqVh > div.OPPzxe > c-wiz > div > div.usGWQd > div > div.lRu31 > span.HwtZe > span:nth-child(" +
                    i +
                    ") > span"
                );
                if (child) {
                    // console.log(child.textContent);
                    text += child.textContent;
                } else break;
            }
            //             console.log('发现元素内容：', targetElement.textContent);
            // localStorage.setItem(new URLSearchParams(window.location.search).get('tl'), text);
            const lines = text.split(/\r?\n/);
            const { cid, ctype } = getHashParams();

            if (cid === "" || ctype === "") {
                console.log("没有id和type参数，不是批量翻译，不执行");
                clearInterval(elementChecker);
                return;
            }
            console.log("ID:", cid, "Type:", ctype);
            let result = [];
            for (let i = 0; i < lines.length; i++) {
                if (lines[i] !== "") result.push(lines[i]);
                else if (lines[i - 1] !== "" && i > 16) result.push("");
            }
            console.log(result);
            let id = cid;
            let type = ctype;
            let country = getUrlParam("tl");
            let title = "";
            let content = "";
            let descript = "";
            if (type === "title") {
                title = result[0];
                console.log(title);
            } else if (type === "content") {
                content = result.slice(0).join("\n");
                console.log(content);
            } else if (type === "descript") {
                descript = result.slice(0).join("\n");
                console.log(descript);
            }

            // 定义请求参数
            const url = "http://127.0.0.1:10086/translate/put"; // 替换为目标 URL
            const data = {
                id: id,
                country: country,
                title: title,
                content: content,
                descript: descript,
            };
            console.log(data);

            // 发送 POST 请求
            fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json;charset=UTF-8", // 声明 JSON 格式‌:ml-citation{ref="1,2" data="citationList"}
                },
                body: JSON.stringify(data), // 序列化数据‌:ml-citation{ref="1,5" data="citationList"}
            })
                .then((response) => {
                    if (!response.ok)
                        throw new Error(`HTTP 错误! 状态码: ${response.status}`);
                    return response.json(); // 解析 JSON 响应‌:ml-citation{ref="1" data="citationList"}
                })
                .then((result) => {
                    console.log("请求成功:", result);
                    try {
                        window.close();
                    } catch {
                        console.log("只能关闭自动打开的网页");
                    }
                })
                .catch((error) => {
                    console.error("请求失败:", error);
                });

            clearInterval(elementChecker);
        }
    }, 500);
};
